/**
* <p>Title: BaseController.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2015</p>
* <p>Company: yihaoxue</p>
* @author victoryu
* @version 1.0
*/
package com.tc.base.controller;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

import com.siysoft.util.COMMON;
import com.siysoft.util.IMap;


/**
 * <p>Title: BaseController</p>
 * <p>Description: </p>
 * <p>Company: yihaoxue</p>
 * @author   victoryu
 */
public abstract class BaseController {
	
	public void success(HttpServletResponse response, String msg){
		try {
			writerJsonData(response, "{\"success\":true,\"msg\":\"" + msg + "\"}");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	/**
	 * @category 格式化response给用户的json数据。
	 * @author victoryu 
	 * @param  code 0:表示成功；其他的错误代码对应，详见艺好学api规范。
	 * @param  msg 基本消息信息
	 * @param  data 实际真正的json数据体。
	 * @return 返回标准的json回复字符串。遇到Json转换异常，返回"CreateJson failed"
	 */
	public String FormatJson(int code,String msg,String data){
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("code", code);
			jsonObj.put("message", msg);
			jsonObj.put("data", data);
			try {
				return Object2Json(jsonObj);
			} catch (Exception e) {
				e.printStackTrace();
				return "CreateJson failed";
			}
	}
	/**
	 * @category 成功时：写好的json信息增加 http头定义，然后Response.write();
	 * @author victoryu
	 * @param response response对象
	 * @param json 要发送的json数据
	 * @param max_age 缓存的时间（毫秒级），0表示不缓存。
	 * @throws Exception 
	 */
	public void responseSuccess(HttpServletResponse response,String json,int max_age){
		try {
			response.setCharacterEncoding("UTF-8");  
			response.setContentType("application/json; charset=utf-8"); 
			response.setHeader("Cache-Control","max-age="+max_age);
			response.setHeader("Cache-Control","max-age="+max_age);
			response.addHeader("Access-Control-Allow-Origin", "*");
			response.getWriter().print(json);
			COMMON.trace("response","success",json);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * @category 失败时：发送错误代码及错误消息
	 * @author victoryu
	 * @throws Exception 
	 */
	public void responseFail(HttpServletResponse response,int code,String msg,String data){
		try {
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("code", code);
			jsonObj.put("message", msg);
			jsonObj.put("data", data);
			response.setCharacterEncoding("UTF-8");  
			response.setContentType("application/json; charset=utf-8"); 
			response.getWriter().print(Object2Json(jsonObj));
			response.addHeader("Access-Control-Allow-Origin", "*");
			COMMON.trace("response","failure",Object2Json(jsonObj));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
	
	public QueryParams getQueryParams(HttpServletRequest request) throws Exception{
		request.setCharacterEncoding("UTF-8");
		QueryParams qp=new QueryParams();
		IMap params = new IMap(request);
		qp.setSort(params.getBoolean("isSort"));
		String sortField;
		String sortDir="ASC";
		String queryId = params.getString("queryId");
		
		if(!StringUtils.isBlank(queryId)){
			qp.setQueryId(params.getString("queryId"));
		}
		else throw new Exception("queryId is NULL"); 
		
		qp.setPagination(params.getBoolean("isPagination"));
		
		Integer pageSize = Integer.valueOf(0);
		pageSize = params.getInt("pageSize");
		
		if(pageSize<1){
			qp.setPageSize(10);
		}
		else qp.setPageSize(pageSize);
		
		Integer page =  Integer.valueOf(0);
		page=params.getInt("page");
		if(page<1){
			qp.setPage(1);
		}
		else qp.setPage(page);
		
		Integer startIndex = Integer.valueOf(0);
		startIndex = Integer
				.valueOf((qp.getPage() - 1) * qp.getPageSize());
		qp.setStartIndex(startIndex);
		if(qp.isSort()){
			sortField=params.getString("sort");
			if(!StringUtils.isBlank(sortField)){
				qp.setSortField(sortField);
			}
			else qp.setSort(false);
			
			sortDir=params.getString("dir");
			
			if("DESC".equals(sortDir.toUpperCase())||"ASC".equals(sortDir.toUpperCase())){
				qp.setDir(sortDir);
			}
			else
				qp.setDir("ASC");
		}
		qp.setParams(params);
		return qp;
		
		
		
	}
//	public void printSuccess(HttpServletResponse response, String msg,String printTemplate){
//		try {
//			writerJsonData(response, "{success:true,msg:'" + msg + "',print:'"+printTemplate+"'}");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	public  void failure(HttpServletResponse response, String msg){
		try {
			writerJsonData(response, "{\"success\":false,\"msg\":\"" + msg + "\"}");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public HttpServletRequest forwardSuccess(HttpServletRequest request,String msg){
		request.setAttribute("message", msg);
		request.setAttribute("success", true);
		return request;
	}
	public HttpServletRequest forwardSuccess(HttpServletRequest request,String title,String msg){
		request.setAttribute("message", msg);
		request.setAttribute("title", title);
		request.setAttribute("success", true);
		return request;
	}
	public HttpServletRequest forwardFailue(HttpServletRequest request,String msg){
		request.setAttribute("message", msg);
		request.setAttribute("success", false);
		return request;
	}
	
	
	/**
	 * 发送Json格式的字符串
	 * author： victoryu
	 * @param response
	 * @param json
	 * @throws Exception 
	 */
	public void writerJsonData (HttpServletResponse response, Object jsonData) throws Exception{
		Object json = "{}";
		
		if(jsonData instanceof Map) {
			JSONObject obj = new JSONObject();
			obj.accumulateAll((Map)jsonData);
			json = obj.toString();
		} else if(jsonData instanceof Collection) {
			json = JSONArray.fromObject(jsonData);
		} else {
			json = jsonData;
		}
		response.setCharacterEncoding("UTF-8");  
		response.setContentType("application/json; charset=utf-8");  
		response.getWriter().print(json);
	}
	
	
	public String Object2Json ( Object jsonData) throws Exception{
		JsonGenerator jsonGenerator = null;
	    ObjectMapper objectMapper = null;
	    objectMapper = new ObjectMapper();
        try {
            jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        jsonGenerator.writeObject(jsonData);
        return objectMapper.writeValueAsString(jsonData);
}
	
	/**
	 * 输出JsonData的字符串。
	 * author： victoryu
	 * @param response
	 * @param jsonData
	 * @throws Exception
	 */
	public void writerJsonString (HttpServletResponse response, String jsonData) throws Exception{
		
		response.setCharacterEncoding("UTF-8");  
		response.setContentType("application/json; charset=utf-8");  
		response.getWriter().print(jsonData);
	}
	

}
